package com.dianban.controller.nengliang;

import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.*;
import com.dianban.service.*;
import com.dianban.utils.CaculateDistanceUtil;
import com.dianban.utils.IpUtils;
import com.dianban.utils.TencentMapUtils;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(value = "ApiCommissionVerifyLogController", description = "美导佣金核销接口")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/commissionVerify/")
public class ApiCommissionVerifyLogController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiCommissionVerifyLogController.class);

    @Autowired
    private FacePayCommissionVerifyLogService facePayCommissionVerifyLogService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private ShoproOrderService shoproOrderService;
    @Autowired
    private JwStoreService storeService;
    @Autowired
    private FacePayConfigService facePayConfigService;
    @Autowired
    private UserService userService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "佣金核销列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "status", value = "核验状态 10 待核验；20已核验；", required = false, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(Integer status, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        // 有效期改成配置
        List<FacePayConfig> facePayConfigList = facePayConfigService.find(120, 1, null);
        Integer effectiveMinute  = 30;
        if (facePayConfigList != null && !facePayConfigList.isEmpty()) {
            effectiveMinute = Integer.parseInt(facePayConfigList.get(0).getValue());
        }
        List<FacePayCommissionVerifyLog> facePayCommissionVerifyLogList = facePayCommissionVerifyLogService.findList(status, user.getId(), null, effectiveMinute);
        return ResultVo.success(facePayCommissionVerifyLogList, "操作成功");
    }

    @ApiOperation(notes = "verify", httpMethod = "POST", value = "佣金核销")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "id", value = "佣金核销id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "query", dataType = "string"),

    })
    @RequestMapping(value = "verify", method = RequestMethod.POST)
    public ResultVo updateStatus(Long id, String code, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        if (code == null) {
            return ResultVo.error(ResultCode.ERROR, "短信验证码不能为空");
        }
        FacePayCommissionVerifyLog facePayCommissionVerifyLog = facePayCommissionVerifyLogService.findById(id);
        if (facePayCommissionVerifyLog == null) {
            return ResultVo.error(ResultCode.ERROR, "佣金核销id错误");
        }
        if (!code.equals(facePayCommissionVerifyLog.getCode())) {
            return ResultVo.error(ResultCode.ERROR, "短信验证码错误");
        }
        if (facePayCommissionVerifyLog.getStatus().equals(20)) {
            return ResultVo.error(ResultCode.ERROR, "佣金核销id已核销");
        }
        facePayCommissionVerifyLogService.verify(facePayCommissionVerifyLog);
        return ResultVo.success("", "操作成功");
    }

    @RequestMapping(value = "/checkIdMatrix", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取检测核验的id关联门店跟我的距离")
    public ResultVo checkIdMatrix(String id, HttpServletRequest request, HttpServletResponse response) {
        logger.info("获取检测核验的id关联门店跟我的距离, id - {}", id);
        Map<String, Object> resultMap = new HashMap<>();
        Boolean checkResult = false;
        try {
            if (StringUtils.isEmpty(id)) {
                return ResultVo.error(ResultCode.ERROR, "核验id不能为空");
            }
            FacePayCommissionVerifyLog commissionVerifyLog = facePayCommissionVerifyLogService.findById(Long.valueOf(id));
            if (commissionVerifyLog == null) {
                return ResultVo.error(ResultCode.ERROR, "未找到核验id的数据不能为空");
            }
            Long offlineOrderId = commissionVerifyLog.getOfflineOrderId();
            Long onlineOrderId = commissionVerifyLog.getOnlineOrderId();
            Long storeId = null;
            if (offlineOrderId != null) {
                FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(offlineOrderId);
                if (facePayStoreOrder != null) {
                    storeId = facePayStoreOrder.getStoreId();
                }
            } else if (onlineOrderId != null) {
                ShoproOrder shoproOrder = shoproOrderService.findById(onlineOrderId);
                if (shoproOrder != null) {
                    storeId = shoproOrder.getStoreId();
                }
            }
            String from = "";
            String ipAddr = IpUtils.getIpAddr(request);
            JSONObject location = TencentMapUtils.location(ipAddr);
            logger.info("当前ip地址：{}", location);
            if (location != null) {
                if (location.get("result") != null) {
                    JSONObject result = JSONObject.parseObject(String.valueOf(location.get("result")));
                    if (result != null) {
                        JSONObject _location = JSONObject.parseObject(String.valueOf(result.get("location")));
                        if (_location != null) {
                            //from = _location.get("lng") + "," + _location.get("lat");
                            from = _location.get("lat") + "," + _location.get("lng");
                        }
                    }
                }
            }
            logger.info("from:{}", from);
            //GlobalCoordinates source = null;
            //if (!StringUtils.isEmpty(from)) {
            //    source = new GlobalCoordinates(Double.valueOf(from.split(",")[1]), Double.valueOf(from.split(",")[0]));
            //}
            // 增加门店经纬度周边排序
            JwStore jwStore = storeService.findById(Long.valueOf(storeId));
            if (storeId == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该门店");
            }
            String matrixValue = "-1";
            if (!StringUtils.isEmpty(from)) {
                if (!StringUtils.isEmpty(jwStore.getLal())) {
                    //jwStore.setMatrix(JSONObject.toJSONString(TencentMapUtils.matrix(from, jwStore.getLal())));
                    //GlobalCoordinates target = new GlobalCoordinates(Double.valueOf(jwStore.getLal().split(",")[1]), Double.valueOf(jwStore.getLal().split(",")[0]));
                    //matrixValue = (String.valueOf(CaculateDistanceUtil.getDistanceMeter(source, target, Ellipsoid.Sphere)));
                    JSONObject jsonObject = TencentMapUtils.baiduTranslate(jwStore.getLal().split(",")[1] + "," + jwStore.getLal().split(",")[0]);
                    if (jsonObject != null) {
                        JSONObject matrix = TencentMapUtils.matrix(from, jsonObject.get("lat")+","+jsonObject.get("lng"));
                        if (matrix != null) {
                            if (matrix.get("distance") != null && !org.springframework.util.StringUtils.isEmpty(matrix.get("distance"))) {
                                matrixValue = JSONObject.toJSONString(matrix.get("distance"));
                            }
                        }
                    }
                }
            }
            logger.info("matrixValue:{}", matrixValue);
            List<FacePayConfig> facePayConfigList = facePayConfigService.find(60, 1, null);
            int count = 3;
            if (facePayConfigList != null && !facePayConfigList.isEmpty()) {
                count = Integer.valueOf(facePayConfigList.get(0).getValue());
            }
            if (!StringUtils.isEmpty(matrixValue)) {
                matrixValue = matrixValue.split("\\.")[0];
            }
            // 转换成公里
            if (Integer.valueOf(matrixValue).intValue()/1000 <= count) {
                checkResult = true;
            }
            resultMap.put("checkResult", checkResult);
            resultMap.put("matrixValue", Integer.valueOf(matrixValue).intValue()/1000);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(resultMap, "获取成功");
    }

    @RequestMapping(value = "/checkFromIdMatrix", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取当前经纬度检测核验的id关联门店跟我的距离")
    public ResultVo checkFromIdMatrix(String from, String id, HttpServletRequest request, HttpServletResponse response) {
        logger.info("获取当前经纬度检测核验的id关联门店跟我的距离, from - {}, id - {}", from, id);
        Map<String, Object> resultMap = new HashMap<>();
        Boolean checkResult = false;
        try {
            if (StringUtils.isEmpty(id)) {
                return ResultVo.error(ResultCode.ERROR, "核验id不能为空");
            }
            FacePayCommissionVerifyLog commissionVerifyLog = facePayCommissionVerifyLogService.findById(Long.valueOf(id));
            if (commissionVerifyLog == null) {
                return ResultVo.error(ResultCode.ERROR, "未找到核验id的数据不能为空");
            }
            Long offlineOrderId = commissionVerifyLog.getOfflineOrderId();
            Long onlineOrderId = commissionVerifyLog.getOnlineOrderId();
            Long storeId = null;
            if (offlineOrderId != null) {
                FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(offlineOrderId);
                if (facePayStoreOrder != null) {
                    storeId = facePayStoreOrder.getStoreId();
                }
            } else if (onlineOrderId != null) {
                ShoproOrder shoproOrder = shoproOrderService.findById(onlineOrderId);
                if (shoproOrder != null) {
                    storeId = shoproOrder.getStoreId();
                }
            }
//            String from = "";
//            String ipAddr = IpUtils.getIpAddr(request);
//            JSONObject location = TencentMapUtils.location(ipAddr);
//            logger.info("当前ip地址：{}", location);
//            if (location != null) {
//                if (location.get("result") != null) {
//                    JSONObject result = JSONObject.parseObject(String.valueOf(location.get("result")));
//                    if (result != null) {
//                        JSONObject _location = JSONObject.parseObject(String.valueOf(result.get("location")));
//                        if (_location != null) {
//                            //from = _location.get("lng") + "," + _location.get("lat");
//                            from = _location.get("lat") + "," + _location.get("lng");
//                        }
//                    }
//                }
//            }
            logger.info("from:{}", from);
            //GlobalCoordinates source = null;
            //if (!StringUtils.isEmpty(from)) {
            //    source = new GlobalCoordinates(Double.valueOf(from.split(",")[1]), Double.valueOf(from.split(",")[0]));
            //}
            // 增加门店经纬度周边排序
            JwStore jwStore = storeService.findById(Long.valueOf(storeId));
            if (storeId == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该门店");
            }
            String matrixValue = "-1";
            if (!StringUtils.isEmpty(from)) {
                if (!StringUtils.isEmpty(jwStore.getLal())) {
                    //jwStore.setMatrix(JSONObject.toJSONString(TencentMapUtils.matrix(from, jwStore.getLal())));
                    //GlobalCoordinates target = new GlobalCoordinates(Double.valueOf(jwStore.getLal().split(",")[1]), Double.valueOf(jwStore.getLal().split(",")[0]));
                    //matrixValue = (String.valueOf(CaculateDistanceUtil.getDistanceMeter(source, target, Ellipsoid.Sphere)));
                    JSONObject jsonObject = TencentMapUtils.baiduTranslate(jwStore.getLal().split(",")[1] + "," + jwStore.getLal().split(",")[0]);
                    if (jsonObject != null) {
                        JSONObject matrix = TencentMapUtils.matrix(from, jsonObject.get("lat")+","+jsonObject.get("lng"));
                        if (matrix != null) {
                            if (matrix.get("distance") != null && !org.springframework.util.StringUtils.isEmpty(matrix.get("distance"))) {
                                matrixValue = JSONObject.toJSONString(matrix.get("distance"));
                            }
                        }
                    }
                }
            }
            logger.info("matrixValue:{}", matrixValue);
            List<FacePayConfig> facePayConfigList = facePayConfigService.find(60, 1, null);
            int count = 3;
            if (facePayConfigList != null && !facePayConfigList.isEmpty()) {
                count = Integer.valueOf(facePayConfigList.get(0).getValue());
            }
            if (!StringUtils.isEmpty(matrixValue)) {
                matrixValue = matrixValue.split("\\.")[0];
            }
            // 转换成公里
            if (Integer.valueOf(matrixValue).intValue()/1000 <= count) {
                checkResult = true;
            }
            resultMap.put("checkResult", checkResult);
            resultMap.put("matrixValue", Integer.valueOf(matrixValue).intValue()/1000);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(resultMap, "获取成功");
    }

}
